// pages/pay/index.js
import { showToast, requestPayment } from "../../utils/asyncWX.js";
import { request } from "../../request/index.js";
import regeneratorRuntime from "../../lib/runtime/runtime";

Page({
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },
  onShow() {
    const address = wx.getStorageSync('address')
    let cart = wx.getStorageSync('cart')||[]
    cart = cart.filter(v => v.checked)
    
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v => {
      totalPrice += v.num*v.goods_price
      totalNum += v.num
    })
    this.setData({ 
      cart,
      totalPrice,
      totalNum,
      address
    })
  },
  async handlePay() {
    try {
      await showToast({title: '没有企业appid (╥﹏╥)'})
      const token = wx.getStorageSync('token')
      if(!token) {
        wx.navigateTo({
          url: '/pages/auth/index'
        })
        return
      }

      // 发起订单请求
      const order_price = this.data.totalPrice
      const consignee_addr = this.data.address.all
      const cart = this.data.cart
      let goods = []
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      const orderParams = { order_price, consignee_addr, goods }
      // 获取订单编号
      const { order_number } = await request({ url: '/my/orders/create', method: 'post', data: orderParams })
      // 发起预支付
      const { pay } = await request({ url: '/my/orders/req_unifiedorder', method: 'post', data: { order_number } })
      // 发起微信支付
      await requestPayment(pay)
      // 查看订单状态
      const res = await request({ url: '/my/orders/chkOrder', method: 'post', data: { order_number } })
      // res 支付成功
      await showToast({ title: res })
     
      let newCart = wx.getStorageSync('cart')
      newCart = newCart.filter(v => !v.checked)
      wx.setStorageSync('cart', newCart);
        
      wx.navigateTo({
        url: '/pages/order/index'
      })
      
    } catch (error) {
      console.log(error);
      await showToast({ title: "支付失败" })
    }

  }
})